package com.hx.vending.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hx.vending.annotation.Accredit;
import com.hx.vending.annotation.AnnotationField;
import com.hx.vending.annotation.Authorization;
import com.hx.vending.bean.AdminTokenModel;
import com.hx.vending.bean.User;
import com.hx.vending.bean.config.Constants;
import com.hx.vending.bean.entity.TokenModel;
import com.hx.vending.service.IFieldService;
import com.hx.vending.service.ITokenService;
import com.hx.vending.service.IUserService;
import com.hx.vending.util.Msg;
import com.hx.vending.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 *自定义拦截器，判断此请求是否有权限
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private ITokenService tokenService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IFieldService fieldService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      /*  System.out.println(request.getRequestURI());*/

        /*String requestContent = getRequestBody(request);
        LoginParam param = map.fromJson(requestContent, LoginParam.class);*/

        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //从header中得到token
        //System.out.println("从header中得到token"+request.getHeader("Authorization"));
        String authorization = request.getHeader(Constants.AUTHORIZATION);
        String accredit = request.getHeader(Constants.ACCREDIT);
        AdminTokenModel adminModel = this.tokenService.getAdminToken(accredit);
       //验证token
        TokenModel model = this.tokenService.getToken(authorization);
        if(method.getAnnotation(Accredit.class) != null){
            if (null == adminModel) {
                returnErrorMessage(response, "未登录");
                return false;
            }
            if(this.tokenService.checkAdminToken(adminModel)){
                //如果token验证成功，将token对应的userId存在request中，便于之后注入
                request.setAttribute(Constants.CURRENT_ADMIN_ID, adminModel.getAdminId());
                return true;
            }else{
                //验证失败
                returnErrorMessage(response, "未登录");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }

        }
        if (method.getAnnotation(Authorization.class) != null) {
            if (null == model) {
                returnErrorMessage(response, "未登录");
                /*response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);*/
                return false;
            }
            // 不是 admin 不能访问 /admin 的接口
            /*if (url.split("/")[1].equals("admin")) {
                if (String.valueOf(model.getUserId()).length() != 3) {
                    System.out.println("ss");
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    return false;
                }
            }*/
            if (this.tokenService.checkToken(model)) {
                User user = userService.selectUserDetailsById(Integer.parseInt(model.getUserId()));
                if(method.getAnnotation(AnnotationField.class) != null){
                    if(ToolUtil.isEmpty(user.getUserFather())){
                        //Integer[] integers = new Integer[0];
                        Integer[] integers = fieldService.selectIdByUserId(user.getUserId());
                        request.setAttribute(Constants.CURRENT_FIELD_ID, integers);
                    }else{
                        String[] strs = user.getUserFieldId().split(",");
                        Integer[] integers = new Integer[strs.length];
                        for (int i = 0;i < strs.length;i++){
                            integers[i] = Integer.parseInt(strs[i]);
                        }
                        request.setAttribute(Constants.CURRENT_FIELD_ID, integers);
                    }
                }
                if(ToolUtil.isEmpty(user.getUserFather())){
                    //如果token验证成功，将token对应的userId存在request中，便于之后注入
                    request.setAttribute(Constants.CURRENT_ACCOUNT_ID,0);
                    request.setAttribute(Constants.CURRENT_USER_ID, model.getUserId());
                }else{
                    request.setAttribute(Constants.CURRENT_ACCOUNT_ID,user.getUserId());
                    request.setAttribute(Constants.CURRENT_USER_ID,user.getUserFather());
                }
                return true;
            }else{
                //验证失败
                returnErrorMessage(response, "未登录");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }

        }
        //如果验证token失败，并且方法注明了Authorization， 返回401错误
       /* if (method.getAnnotation(Authorization.class) != null) {
            if(!this.tokenService.checkToken(model)){

            }
        }*/
        return true;
    }

    private void returnErrorMessage(HttpServletResponse response, String errorMessage) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        //Get the printwriter object from response to write the required json object to the output stream
        PrintWriter out = response.getWriter();
        //Assuming your json object is **jsonObject**, perform the following, it will return your json object
        ObjectMapper mapper = new ObjectMapper();
        Msg msg = new Msg();
        msg.setCode(HttpServletResponse.SC_UNAUTHORIZED);
        msg.setMsg("未登录");
        String jsonOfRST = mapper.writeValueAsString(msg);
        out.print(jsonOfRST);
        out.flush();
    }
}
